<?php
require_once 'TVB/pms/pdes/common/util/mis/MISException.class.php';

class MisMapping
{
    public static $mapping_file = '/data/pms/pdes/conf/mis_mapping.xml';
    static $mapping_xml_data = array();

    public static function init($type, $language)/*{{{*/
    {
        if (empty($type)) {
            throw new MISException("Can't mapping because type is empty.\n");
        }

        #load mapping data  
        if (empty(self::$mapping_xml_data)) {
            if (file_exists(self::$mapping_file)) {
                self::$mapping_xml_data = simplexml_load_file(self::$mapping_file);
            }else {
                throw new MISException("mapping config xml file is not exists.\n");
            }
        }
        
        #type mapping
        if (property_exists(self::$mapping_xml_data->DB, $type)) {
            $mapping = self::$mapping_xml_data->DB->$type;
            if ($language) {
                if (property_exists($mapping, $language)) {
                    $mapping = $mapping->$language;
                } else {
                    throw new MISException("Can't mapping because language({$language}) is not exists in type({$type}).\n");
                }
            } 
            return $mapping;
        } else {
            throw new MISException("Can't mapping because type is not exists.\n");
        }
    }/*}}}*/

    public static function getMapping($type, $data, $language='') /*{{{*/
    {
        try {
            if (!is_object($data) || empty($data)) {
                throw new MISException("Can't mapping because input data is error.\n");
            } 

            #load mapping data
            $mapping = self::init($type, $language);

            #get type mapping data
            $ret = null;
            foreach (get_object_vars($mapping) as $key=>$value) {
                if ($value) {
					$attr = $mapping->$key->attributes();
					$func_name = property_exists($attr, 'func_name') ? ((string)$attr->func_name)     : '';
					$mandatory = property_exists($attr, 'mandatory') ? ((int)$attr->mandatory?1:0)    : 0;
					$allownull = property_exists($attr, 'null')      ? ((string)$attr->null=='no'?0:1): 1;

					#echo " $key mandatory: $mandatory \n"; 
					#echo " $key null: $allownull \n";

					$pass_one = false;
					if(property_exists($data, $value)){  // mis exists
						if(get_object_vars($data->$value)){ // has property
							$attr = $data->$value->attributes();
							if(property_exists($attr, 'OPTIONS_ID')){
								try{
									$ret->$key = self::getOptionsMappingId($attr->OPTIONS_ID,(string)$data->$value);
								}catch(MISException $e){
									if($allownull){
										$ret->$key = '';
									}else{
                                        throw $e;
									}
								}
								$pass_one = true;
							}
						}

						if(!$pass_one){
							if($func_name){
								$ret->$key = self::$func_name($data->$value);
							}else{
								$ret->$key = (string)$data->$value;
							}
						}
					}else{
                        if ($func_name) {
							$ret->$key = self::$func_name((object) array());
                        } else if(!$mandatory){
							$ret->$key = '';
						}else{
							throw new MISException("Can't mapping because property({$value}) is not exists in xml data.\n");
						}
					}

					if(!$allownull && empty($ret->$key)) throw new MISException("Can't mapping because property({$value}} not allow null.\n"); 
                }
            }
    
            return $ret;
        } catch(MISException $e) {
            throw $e; 
        }
    }/*}}}*/

    public function formatLogData($type, array $data, $language='')/*{{{*/
    {
		$ret = array();
		$mapping = self::init($type, $language);

		foreach (get_object_vars($mapping) as $key=>$value) {
			$attr = $mapping->$key->attributes();
			if (property_exists($attr, 'ui_name')) {
				if (array_key_exists($key, $data)) {
					$ret[(string) $key] = (string) $data[$key]; 
				}
			}
		}

		return $ret;
    }/*}}}*/

    public function getUiName($type, $language='')/*{{{*/
    {
		$ret = array();
		$mapping = self::init($type, $language);

		foreach (get_object_vars($mapping) as $key=>$value) {
			$attr = $mapping->$key->attributes();
			if (property_exists($attr, 'ui_name')) {
				$ret[(string) $key] = (string) $attr->ui_name; 
			}
		}

		return $ret;
    }/*}}}*/

    public function getUIMapping($type, $data, $language='')/*{{{*/
    {
        try {
            if (!is_array($data) || empty($data)) {
                throw new MISException("Error because input data is not correct.\n");
            }

            #load mapping data
            $mapping = self::init($type, $language);

            #UI mapping
            $ret = NULL;
            foreach (get_object_vars($mapping) as $key=>$value) {
                $attr = $mapping->$key->attributes();
                if (property_exists($attr, 'ui_name')) {
                    if (array_key_exists($key, $data)) {
                        $ret[(string) $attr->ui_name] = (string) $data[$key]; 
                    }
                }
            }

            return $ret;
        } catch (MISException $e) {
            throw new MISException('UIMapping error:'.$e->getMessage());
            return $e->getMessage();
        }
    }/*}}}*/

    public function getRecoverSql($type, $data, $language='')/*{{{*/
    {
        $where = array();

        try {
            if (!is_object($data) || empty($data)) {
                throw new MISException("Error because input data is not correct.\n");
            }

            #where
            if (method_exists($data, 'getPrimaryKey')) {
                $primary_key = $data->getPrimaryKey();
                foreach ($primary_key as $primary) {
                    if (property_exists($data, $primary)) {
                        $where[] = $primary . "='" . $data->$primary . "'";
                    } else {
                        throw new MISException("primary key error.");
                    }
                }

                if (empty($where)) {
                    throw new MISException("primary key error.");
                }
            } else {
                throw new MISException("method(getPrimaryKey) is not exists in objectRecord.");
            }


            #load mapping data
            $mapping = self::init($type, $language);

            #UI mapping
            $ret = array();
            foreach (get_object_vars($mapping) as $key=>$value) {
                $attr = $mapping->$key->attributes();
                if (property_exists($attr, 'ui_name')) {
                    if (property_exists($data, $key)) {
                        $ret[] = $key . "='" . (string)$data->$key . "'";
                    } else {
                        throw new MISException("Create recover sql error:input data error.");
                    }
                }
            }

            if (!empty($ret)) {
                return "UPDATE `{$type}` SET " . implode(',', $ret) . ' WHERE ' . implode(' AND ', $where);
            } else {
                return '';
            }
        } catch (MISException $e) {
            throw new MISException('Create recover sql error:'.$e->getMessage());
            return $e->getMessage();
        }
    }/*}}}*/

    public function getCastRoleMapping($group_id)/*{{{*/
    {
        $cast_role = array(
            '0'     => array('id'=>1),
            '1'     => array('id'=>2),
            '2'     => array('id'=>16),
            '3'     => array('id'=>10),
            '4'     => array('id'=>11),
            '5'     => array('id'=>12),
            '6'     => array('id'=>3),
            '7'     => array('id'=>4),
            '8'     => array('id'=>5),
            '9'     => array('id'=>6),
            '10'    => array('id'=>17),
            '11'    => array('id'=>18),
            '21'    => array('id'=>14),
            '22'    => array('id'=>7),
            '23'    => array('id'=>8),
            '24'    => array('id'=>9),
            '25'    => array('id'=>15),
            '26'    => array('id'=>19),
            '27'    => array('id'=>20),
            '28'    => array('id'=>21),
        );

        if (array_key_exists($group_id, $cast_role)) {
            if (array_key_exists('id', $cast_role[$group_id])) {
                return $cast_role[$group_id]['id'];
            } else {
                throw new MISException("getCastRoleMapping failure[MIS Group ID:$group_id]:relation is not exists.");
            }
        } else {
            throw new MISException("getCastRoleMapping failure[MIS Group ID:$group_id]:group_id is not exists.");
        }
    }/*}}}*/

    public function get_air_date($xml_obj) /*{{{*/
    {
        if (property_exists($xml_obj, 'TELECAST_DATE') && property_exists($xml_obj, 'AIR_TIME_HHMMSS')) {
            $date = explode('-', $xml_obj->TELECAST_DATE);
            $time = explode(':', $xml_obj->AIR_TIME_HHMMSS);
            $unixtime = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);   //bug 4169
            /*if ($unixtime < time()) { //bug 4049 deleted Air_date checking by Keith
                throw new MISException("MIS's Air_Date(".date('Y-m-d H:i:s', $unixtime).") should after current time.");
            }*/
        } else {
            $unixtime = time();
        }

        return date('Y-m-d H:i:s', $unixtime);
    }/*}}}*/

    public function getOptionsMappingId($options_id,$value)/*{{{*/
    {
        $sql = "SELECT `item_id` FROM `mis_options` WHERE `id`=:id";
        $param = array(':id' => $options_id);
        $result = Model::selectBySql($sql, $param);

        if (isset($result[0]) && $result[0]['item_id']>0) {
            return $result[0]['item_id'];
        } else {
            throw new MISException("Can't mapping because option_id({$options_id}:{$value}) is not exists in pdes.\n");
        }
    }/*}}}*/
}
?>
